<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Log;
use Tests\CreatesApplication;

class AuthenticationControllerTest extends BaseTestCase
{
  use CreatesApplication;

  public function testShouldRegisterAndActivateUser()
  {
    Log::debug(__METHOD__);

    $parameters = [
      'name' => 'Catlin Snow',
      'email' => 'caitlin.snow@starlab.com',
      'password' => 'iamkillerfrost',
    ];
    $response = $user = null;
    $token = '';
    $headers = [];

    $response = $this->json('POST', '/api/v1/register', $parameters);
    $response->assertStatus(201);
    if (config('coreapi.registered_user_confirmation_email')) {
      $token = $response->json(['coreapi_token']);
      $headers = [
        'Authorization' => 'Bearer ' . $token,
      ];
      $response = $this->withHeaders($headers)->json(
        'GET',
        '/api/v1/activate?email=' . $parameters['email'] . '&locale=it_IT'
      );
    }
    $user = User::where('email', $parameters['email'])->first();

    $this->assertTrue($user->active);
  }

  public function testShouldLoginUser()
  {
    Log::debug(__METHOD__);

    $response = null;
    $credentials = [];
    $credentials = [
      'email' => 'caitlin.snow@starlab.com',
      'password' => 'iamkillerfrost',
    ];

    $response = $this->json('POST', '/api/v1/login', $credentials);

    $response->assertStatus(200);
  }

  public function testShouldReturnUser()
  {
    Log::debug(__METHOD__);

    $response = null;
    $token = '';
    $headers = [];
    $token = $this->getToken();
    $headers = [
      'Authorization' => 'Bearer ' . $token,
    ];

    $response = $this->withHeaders($headers)->json('GET', '/api/v1/authenticatedUser');
    $response->assertStatus(200);

    $this->assertArrayHasKey('user', $response->json());
  }

  public function testShouldLogoutUser()
  {
    Log::debug(__METHOD__);

    $response = null;
    $token = '';
    $headers = [];
    $token = $this->getToken();
    $headers = [
      'Authorization' => 'Bearer ' . $token,
    ];

    $response = $this->withHeaders($headers)->json('GET', '/api/v1/logout');
    $response->assertStatus(200);

    // User::where('email', 'caitlin.snow@starlab.com')->delete();
  }

  private function getToken(): string
  {
    $credentials = $response = null;
    $credentials = [
      'email' => 'caitlin.snow@starlab.com',
      'password' => 'iamkillerfrost',
    ];

    $response = $this->json('POST', '/api/v1/login', $credentials);

    return $response->json(['coreapi_token']);
  }
}
